package com.shenhaofeng.app.utils;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

/**
 * Fragment助手工具
 * Created by Administrator on 2016/3/31.
 */
public class FragmentHelper {


    /**
     * 通过tag创建或者恢复fragment的实例
     *
     * @param context
     * @param manager
     * @param tag
     * @param cls
     * @param args
     * @param <F>
     * @return
     */
    public static <F extends Fragment> F findFragmentByTag(Context context, FragmentManager manager, String tag, Class<F> cls, Bundle args) {
        Fragment fragment = manager.findFragmentByTag(tag);
        if (fragment == null) {
            fragment = Fragment.instantiate(context, cls.getName(), args);
            manager.beginTransaction().add(fragment, tag).commit();
        }
        try {
            return cls.cast(fragment);
        } catch (ClassCastException e) {
            fragment = Fragment.instantiate(context, cls.getName());
            return cls.cast(fragment);
        }
    }


    /**
     * 通过tag创建或者恢复fragment的实例
     *
     * @param context
     * @param manager
     * @param tag
     * @param cls
     * @param <F>
     * @return
     */
    public static <F extends Fragment> F findFragmentByTag(Context context, FragmentManager manager, String tag, Class<F> cls) {
        return findFragmentByTag(context, manager, tag, cls, null);
    }


    /**
     * 通过id创建或者恢复Fragment实例
     *
     * @param context
     * @param manager
     * @param id
     * @param cls
     * @param args
     * @param <F>
     * @return
     */
    public static <F extends Fragment> F findFragmentById(Context context, FragmentManager manager, int id, Class<F> cls, Bundle args) {
        Fragment fragment = manager.findFragmentById(id);
        if (fragment == null) {
            fragment = Fragment.instantiate(context, cls.getName(), args);
            manager.beginTransaction().add(id, fragment).commit();
        }
        try {
            return cls.cast(fragment);
        } catch (ClassCastException e) {
            fragment = Fragment.instantiate(context, cls.getName());
            return cls.cast(fragment);
        }
    }


    /**
     * 通过id创建或者恢复Fragment实例
     *
     * @param context
     * @param manager
     * @param id
     * @param cls
     * @param <F>
     * @return
     */
    public static <F extends Fragment> F findFragmentById(Context context, FragmentManager manager, int id, Class<F> cls) {
        return findFragmentById(context, manager, id, cls, null);
    }


    public static <F extends Fragment> F attachLogicFragment(Context context, FragmentManager manager, Class<F> cls, String tag) {
        return findFragmentByTag(context, manager, tag, cls);
    }

}